package com.qf.dao.Impl;

import com.qf.dao.ProductDao;
import com.qf.pojo.Product;
import com.qf.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class ProductDaoImpl implements ProductDao {

    private QueryRunner queryRunner = new QueryRunner();
    @Override
    public List<Product> findAll() {
        try {
            DBUtils.begin();
            String sql = "select  *  from t_product ORDER BY priority desc";
            List<Product> productList = queryRunner.query(DBUtils.getConnection(),
                    sql,
                    new BeanListHandler<>(Product.class));
            DBUtils.commit();
            return productList;
        } catch (SQLException e) {
            e.printStackTrace();
            DBUtils.rollback();
        }
        return null;
    }

    @Override
    public Product findById(String id) {
        try {
            DBUtils.begin();
            String sql = "select  *  from t_product where id = ?";
            Product product = queryRunner.query(DBUtils.getConnection(),
                    sql,
                    new BeanHandler<>(Product.class),
                    Integer.parseInt(id));
            DBUtils.commit();
            return product;
        } catch (SQLException e) {
            e.printStackTrace();
            DBUtils.rollback();
        }
        return null;
    }
}
